#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：16.在协程种允许同步爬虫任务.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-08 15:03
'''
import asyncio

import requests # 同步网络爬虫库：第三方包，需要自己下载
url_list = [
    "https://ww2.sinaimg.cn/mw690/008Dx8Yely1hre748fydoj30u00k0q65.jpg",
    "https://ww4.sinaimg.cn/mw690/008Dx8Yely1hrniembn9pj30gf0g8tbv.jpg",
    "https://wx1.sinaimg.cn/mw690/008Dx8Yely1hrp5nr0s79j30og0ogn08.jpg",
]

async def get_image(url:str):
    print("任务启动，抓取的图片地址为：", url)
    future = loop.run_in_executor(None, requests.get, url)
    response = await future

    file_name = url.rsplit("/")[-1]
    with open(file_name, "wb") as file:
        file.write(response.content)
        print("下载完成：", url)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    task_list = [loop.create_task(get_image(url)) for url in url_list]
    loop.run_until_complete(asyncio.wait(task_list))

"""
    以上代码只是演示用，不建议在真实项目种混合使用协程/线程
"""